package io.renren.modules.h5.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.exception.RRException;
import io.renren.common.utils.BASE64DecodedMultipartFile;
import io.renren.common.utils.R;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

/**
 * 展会
 *
 * @author whc
 * @email hucheng_86@126.com
 * @date 2019-04-03 22:37:46
 */
@Controller
@RequestMapping("/h5")
public class FileUploadController {
    @Autowired
    private SysOssService sysOssService;

    /**
     * 文件上传
     * @param
     * @return
     */
    @RequestMapping("upload")
    @ResponseBody
    public JSONObject upload(String base64,String type) {
        try {
            return recog(base64,type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 翔云名片识别接口
     * @throws IOException
     */
    public JSONObject recog(String base64,String type) throws IOException {
        String imgUrl = "";
        //用户ocrKey
        String key = "QxMMViqG7CxNjK9e3fFk1t";
        // 用户ocrSecret
        String secret = "9baeca9e62fb487d84cc9b23c0339554";
        //产品类型 需要修改为对应产品类型值(例如:二代证正面为"2"。详见文档说明)
        String typeId = "20";
        String format = "json";
        //http接口调用地址需更换为对应产品接口url
        String url = "http://netocr.com/api/recogliu.do";

        //上传文件
        try {
            imgUrl = upload(base64ToMultipart(base64));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String result = doPost(url, base64, key, secret, typeId, format);

        /*RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url("http://netocr.com/api/recogliu.do")
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();*/
        //String result = response.body().string();
        //System.out.println(result);
        //String json = response.body().string();
        //String result = "{\"message\":{\"status\":1,\"value\":\"msg\"},\"cardsinfo\":[{\"charname\":\"姓名\",\"company\":\"公司\",\"JobTitle\":\"职位\",\"aEmail\":\"邮箱\",\"mobile\":\"13141233803\",\"address\":\"地址\",\"mingpiandizhi\":\"图片\"}]}";
        System.out.println(result);
        Map maps = (Map) JSON.parse(result);
        Map message = (Map)maps.get("message");
        Integer status = (Integer)message.get("status");
        String msg = (String)message.get("value");
        JSONArray cardsinfo = (JSONArray)maps.get("cardsinfo");
        JSONObject obj = new JSONObject();
        //obj.put("status",status);
        obj.put("status",status);
        obj.put("msg",msg);
        obj.put("info",cardsinfo);
        obj.put("imgUrl",imgUrl);
        return obj;
    }

    public static String doPost(String url, String img, String key,String secret, String typeId, String format) {
        String result = "";
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            // 1.创建httpclient对象
            HttpPost post = new HttpPost(url);
            // 2.通过url创建post方法
            if("json".equalsIgnoreCase(format)){
                post.setHeader("accept", "application/json");
            }else if("xml".equalsIgnoreCase(format)||"".equalsIgnoreCase(format)) {
                post.setHeader("accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            }

            //实例化实体构造器
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //设置浏览器兼容模式
            builder.addPart("img",new StringBody(img, ContentType.create("text/plain", Consts.UTF_8)));
            //添加"img"字段及其值
            builder.addPart("key", new StringBody(key, ContentType.create("text/plain", Consts.UTF_8)));
            //添加"key"字段及其值
            builder.addPart("secret", new StringBody(secret, ContentType.create("text/plain", Consts.UTF_8)));
            //添加"secret"字段及其值
            builder.addPart("typeId", new StringBody(typeId, ContentType.create("text/plain", Consts.UTF_8)));
            //添加"typeId"字段及其值
            builder.addPart("format", new StringBody(format, ContentType.create("text/plain", Consts.UTF_8)));
            //添加"format"字段及其值
            HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
            //设置请求的编码格式，并构造实体

            post.setEntity(reqEntity);
            // 4.执行post方法，返回HttpResponse的对象
            CloseableHttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                System.out.println("服务器返回异常");
            }

            try {
                // 6.关闭资源
                HttpEntity e = response.getEntity();
                if (e != null) {
                    InputStream instream = e.getContent();
                    instream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        //7.返回识别结果
        return result;
    }

    //上传文件
    public String upload(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        sysOssService.save(ossEntity);

        return url;
    }

    /**
     * base64格式图片转MultipartFile
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
